//
//  DLMachineDetailVC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/26.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLMachineDetailVC.h"
#import "DLMachineBaseCell.h"
#import "DLMachineNormalTC.h"
#import "DLMachineInfoTC.h"
#import "DLMachineChartsTC.h"
#import "DLMachineVideoTC.h"
#import "DLMachineImageTC.h"
#import "DLMachineFormTC.h"
#import "DLSingleSelectTC.h"
#import "DLAboutRecSV.h"
#import "DLOpinionReportVC.h"

#import "DLMachineKeyboardView.h"
#import "SocketIOHandler.h"
#import "DLMachineModel.h"

#import "DLModifyPasswordVC.h"
@interface DLMachineDetailVC ()<DLMachineKeyboardViewDelegate,ZFTableViewCellDelegate>

//zfplayer
@property (nonatomic, strong) ZFPlayerController *player;

@property (nonatomic, strong) ZFPlayerControlView *controlView;

@property (nonatomic, strong) NSMutableArray *urls;

@property (nonatomic, assign) BOOL isCreatZFPlayer;

/****************/

@property (nonatomic, strong) DLMachineKeyboardView *keyboardView;

@property (nonatomic, strong) DLAboutRecSV *aboutRecSV;

@property (nonatomic, assign) BOOL isUserDisconnect;

@property (nonatomic, strong) NSMutableArray *machineDataSource;

@property (nonatomic, assign) CGFloat transformY;

@property (nonatomic, assign) CGFloat duration;

@property (nonatomic, assign) BOOL isAutoScroll;

@property (nonatomic, strong) UIView *falseNavView;

@property (nonatomic, assign) double hiddenNavHeight;

@property (nonatomic, assign) CGFloat visibleAreaHeight;

@property (nonatomic, assign) NSInteger serverMsgCount;

@property (nonatomic, strong) NSMutableArray *serverDataArray;

@end

@implementation DLMachineDetailVC

- (void) sendTextToServer:(NSString *)msg {
    
    if ([msg isEqualToString:@"我要反馈"]) {
        DLOpinionReportVC *orvc = [DLOpinionReportVC new];
        [self.navigationController pushViewController:orvc animated:YES];
        self.keyboardView.dlTextView.text = @"";
        return;
    }
    
    [self.urls addObject:[NSURL URLWithString:@""]];
    NSString *uniqueId = [DLKeyChainManager readUUID];
    if (isEmpty(uniqueId)) {
        uniqueId = [DLKeyChainManager createUUID];
        [DLKeyChainManager saveUUID:uniqueId];
    }
    
    NSMutableDictionary *socketDic = [NSMutableDictionary dictionary];
    [socketDic setObject:uniqueId forKey:@"user"];
    [socketDic setObject:uniqueId forKey:@"devicecode"];
    [socketDic setObject:uniqueId forKey:@"chatuuid"];
    [socketDic setObject:@"1" forKey:@"online"];
    [socketDic setObject:@"ios" forKey:@"channel"];
    [socketDic setObject:msg forKey:@"client"];
    [socketDic setObject:@(1) forKey:@"msgtype"];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:socketDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *sendMsg = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"给服务端发送的消息是：%@", sendMsg);
    [self.socket emit:@"message" with:@[sendMsg]];
    
    DLMachineModel *model = [DLMachineModel new];
    model.msgFrom = SocketMsgFrom_self;
    model.msgType = SocketMsgType_text;
    model.content = msg;
    [self.machineDataSource addObject:model];
    [self.plainTableView reloadData];
    [self tableviewScrollToLastRow];
    
    self.serverMsgCount = 0;
    [self.serverDataArray removeAllObjects];
}

- (void) dlTextViewShouleReturn:(NSString *)currentText {
    
    if (currentText.length == 0) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"请不要发送空消息" duration:1 position:CSToastPositionCenter];
        return;
    }
    
    kuserManager.isLastMsgVoice = NO;
    [self sendTextToServer:currentText];
    
    self.keyboardView.dlTextView.text = @"";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.hiddenNavHeight = 0.0;
    self.serverMsgCount = 0;
    self.serverDataArray = [NSMutableArray array];
    
    [self initDataSource];
    [self setUpNav];
    [self layoutSubControls];
//    [self doSomething];
}
- (void) iflyDidTransformVoiceToString:(NSNotification*)notify {
    
    NSString *clientOriginMsg = [NSString stringWithFormat:@"%@", notify.object];
    NSString *clientMsg = [clientOriginMsg substringFromIndex:clientOriginMsg.length - 1];
    NSLog(@"%@", clientMsg);
    
    //这里判断最后一个标点，如果有就不发送。
    if ([clientMsg isEqualToString:@"。"] ||
        [clientMsg containsString:@"."] ||
        [clientMsg containsString:@"！"] ||
        [clientMsg containsString:@"!"] ||
        [clientMsg containsString:@"？"] ||
        [clientMsg containsString:@"?"]) {
        NSLog(@"有标点回调一次，没标点也要回调一次，你脑子瓦塔了吗？");
        return;
    }
    kuserManager.isLastMsgVoice = YES;
    
    //将小雨换成小语（部分情况）
    if ([clientOriginMsg isEqualToString:@"小雨小雨"]) {
        clientOriginMsg = @"小语小语";
    } else if ([clientOriginMsg isEqualToString:@"小雨"]) {
        clientOriginMsg = @"小语";
    }
    [self sendTextToServer:clientOriginMsg];
}
- (void) tableviewReloadData {
    [self.plainTableView reloadData];
}
- (void) doSomething {
    
    
//    wss://www.delongra.com
//    http://10.0.0.100:49092
    
    NSInteger isDistributionService = 1;
    NSURL* url = [[NSURL alloc] initWithString:isDistributionService == 1?@"wss://www.delongra.com:49092":@"http://10.0.0.100:49092"];
    SocketManager* manager = [[SocketManager alloc] initWithSocketURL:url config:@{@"log": @NO, @"compress": @YES}];
    SocketIOClient* socket = manager.defaultSocket;
    self.manager = manager;
    self.socket = socket;
    
    // socket 连接服务器
    [self.socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
        NSLog(@"socket connected   连接成功");
    }];
    [self.socket connect];

    // socket 断开连接
    [self.socket on:@"disconnect" callback:^(NSArray* data, SocketAckEmitter* ack) {
        NSLog(@"socket disconnect   断开连接");
    }];

    [self.socket on:@"reconnect" callback:^(NSArray *data, SocketAckEmitter *ack) {
        NSLog(@"socket reconnect   重连中...");
    }];
    
    //你个龟儿子 不用weakself真的会循环引用
    kWeakSelf;
    [self.socket on:@"message" callback:^(NSArray* dataArr, SocketAckEmitter* ack) {
        NSLog(@"收到消息");
        NSLog(@"%@", dataArr);
        
        self.serverMsgCount++;
        NSLog(@"===%ld", self.serverMsgCount);
        NSString *string = [dataArr firstObject];
        NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        
        if (self.serverMsgCount < 2) {
            NSLog(@"服务器返回了一条数据");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSLog(@"收到第1条消息的时间：%@", [NSDate date]);
                [weakSelf dealSocketMsg:dic];
            });
        } else {
            NSLog(@"服务器返回了多条数据");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((self.serverMsgCount - 1) *1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf dealSocketMsg:dic];
            });
        }
    }];
}

- (void) dealSocketMsg:(NSDictionary *)dataDic {
    
    DLMachineModel *model = [DLMachineModel configModel:dataDic];
    
    //关联推荐特殊处理
    if (self.aboutRecSV.hidden == NO) {
        //关联推荐是显示的，
        [self resetAboutSVYAndTableViewHeight];
    }

    if (model.code.integerValue == 6) {
        //关联推荐sv的显示
        NSLog(@"有关联推荐");
        [self configAboutSV:model];
    }
    
    if (model.msgType == SocketMsgType_video) {
        //视频特殊处理
        if (self.isCreatZFPlayer == NO) {
            [self layoutVideoControls];
            self.isCreatZFPlayer = YES;
        }
        
        NSDictionary *dataDic = model.resultDic;
        NSString *videoUrl = [NSString stringWithFormat:@"%@", dataDic[@"videourl"]];
        
        [self.urls addObject:[NSURL URLWithString:videoUrl]];
    } else {
        [self.urls addObject:[NSURL URLWithString:@""]];
    }
    
    if (model.msgType == SocketMsgType_kLineChart) {
        //k线特殊处理
        NSLog(@"k线特殊处理");
        DLMachineModel *kLineExplainModel = [DLMachineModel new];
        kLineExplainModel.msgType = SocketMsgType_text;
        kLineExplainModel.content = [model configKlineDataWithModel:model];
        kLineExplainModel.msgFrom = SocketMsgFrom_other;
        kLineExplainModel.isKLineMsg = model.isKLineMsg;
        kLineExplainModel.isGoUp = model.isGoUp;
        kLineExplainModel.currentClose = model.currentClose;
        kLineExplainModel.upOrDownPercent = model.upOrDownPercent;
        kLineExplainModel.upOrDownNum = model.upOrDownNum;
        
        [self.machineDataSource addObject:kLineExplainModel];
        
        //视频的，这个累赘
        [self.urls addObject:[NSURL URLWithString:@""]];
        
        [self.machineDataSource addObject:model];
        
        [self.plainTableView reloadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self tableviewScrollToLastRow];            
        });
        return;
    }
    
    [self.machineDataSource addObject:model];
    
    [self.plainTableView reloadData];
    [self tableviewScrollToLastRow];
}
- (void) layoutVideoControls {
    //zfplayer
//    playerManager
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
//    KSMediaPlayerManager *playerManager = [[KSMediaPlayerManager alloc] init];
//    ZFIJKPlayerManager *playerManager = [[ZFIJKPlayerManager alloc] init];
    
    ZFPlayerControlView *controlView = [ZFPlayerControlView new];
    self.controlView = controlView;
    
    self.player = [ZFPlayerController playerWithScrollView:self.plainTableView playerManager:playerManager containerViewTag:100];
    self.player.controlView = self.controlView;
    self.player.assetURLs = self.urls;
    self.player.shouldAutoPlay = NO;
    self.player.playerDisapperaPercent = 1.0;
    
    @weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        NSLog(@"全屏播放？？？？？");
        @strongify(self)
        [self setNeedsStatusBarAppearanceUpdate];
        [UIViewController attemptRotationToDeviceOrientation];
        self.plainTableView.scrollsToTop = !isFullScreen;
    };
    
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @strongify(self)
        NSLog(@"播放结束了吗？？");
        [self.player stopCurrentPlayingCell];
    };
    
    
    self.player.playerPlayFailed = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, id  _Nonnull error) {
        NSLog(@"播放失败");
    };
}

- (void) setUpNav {
//    self.titleView.title = @"小龙";
    
}
- (void) layoutSubControls {
    
    self.view.backgroundColor = kDLMachineTableAndCellBgColor;
//    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *falseNavView = [UIView new];
    falseNavView.frame = CGRectMake(0, 0, kScreenWidth, kHeightNavigation);
    falseNavView.backgroundColor = kColorRGB(242, 242, 242);
    [self.view addSubview:falseNavView];
    self.falseNavView = falseNavView;
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(10, kHeightNavigationStatusBar + (44 - 40) / 2, 40, 40);
    [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:[UIImage imageNamed:@"nav_back_black"] forState:UIControlStateNormal];
    [falseNavView addSubview:backButton];
    
    UIImageView *titleImageView = [UIImageView new];
    titleImageView.frame = CGRectMake((falseNavView.width - 25) / 2, kHeightNavigationStatusBar + (44 - 26) / 2, 25, 26);
    titleImageView.image = [UIImage imageNamed:@"robot_head"];
    [falseNavView addSubview:titleImageView];
    
    DLMachineKeyboardView *keyboardView = [[DLMachineKeyboardView alloc] initWithFrame:CGRectMake(0, kScreenSafeAreaHeight - 84, kScreenWidth, 84)];
    keyboardView.delegate = self;
    [self.view addSubview:keyboardView];
    self.keyboardView = keyboardView;
    
    self.plainTableView.frame = CGRectMake(0, falseNavView.height, kScreenWidth, kScreenSafeAreaHeight - keyboardView.height - falseNavView.height);
    self.plainTableView.backgroundColor = kDLMachineTableAndCellBgColor;
//    self.plainTableView.backgroundColor = kColorRGB(250, 250, 250);
    self.plainTableView.tableFooterView = [UIView new];
    self.plainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.plainTableView registerClass:[DLMachineNormalTC class] forCellReuseIdentifier:@"DLMachineNormalTC"];
    [self.plainTableView registerClass:[DLMachineInfoTC class] forCellReuseIdentifier:@"DLMachineInfoTC"];
    [self.plainTableView registerClass:[DLMachineChartsTC class] forCellReuseIdentifier:@"DLMachineChartsTC"];
    [self.plainTableView registerClass:[DLMachineVideoTC class] forCellReuseIdentifier:@"DLMachineVideoTC"];
    [self.plainTableView registerClass:[DLMachineImageTC class] forCellReuseIdentifier:@"DLMachineImageTC"];
    [self.plainTableView registerClass:[DLMachineFormTC class] forCellReuseIdentifier:@"DLMachineFormTC"];
    [self.plainTableView registerClass:[DLSingleSelectTC class] forCellReuseIdentifier:@"DLSingleSelectTC"];
    [self.plainTableView registerClass:[DLMachineBaseCell class] forCellReuseIdentifier:@"DLMachineBaseCell"];
    [self.view addSubview:self.plainTableView];
    
    kWeakSelf;
    DLAboutRecSV *aboutRecSV = [[DLAboutRecSV alloc] initWithFrame:CGRectMake(0, keyboardView.top - 40, kScreenWidth, 40)];
    aboutRecSV.hidden = YES;
    [self.view addSubview:aboutRecSV];
    self.aboutRecSV = aboutRecSV;
    //你个龟儿子 不用weakself真的会循环引用
    aboutRecSV.recButtonClickBlock = ^(NSInteger buttonTag) {
        //关联推荐点击
        [weakSelf exactIntent:buttonTag];
    };
}
- (void)backButtonClick {
    [self backPreviousPage];
}
- (void)zf_playTheVideoAtIndexPath:(NSIndexPath *)indexPath {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"playVideoNotification" object:nil];
    
    [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
}
/// play the video
- (void)playTheVideoAtIndexPath:(NSIndexPath *)indexPath scrollToTop:(BOOL)scrollToTop {
    
    [self.player playTheIndexPath:indexPath scrollToTop:scrollToTop];
    
    DLMachineModel *model = self.machineDataSource[indexPath.row];
    
    NSDictionary *dataDic = model.resultDic;
    NSString *titleString = [NSString stringWithFormat:@"%@", dataDic[@"title"]];
    NSString *imageBase64String = [NSString stringWithFormat:@"%@", dataDic[@"head_img"]];
    NSArray *arr = [imageBase64String componentsSeparatedByString:@","];
    // 将base64字符串转为NSData
    NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:[arr lastObject] options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
    // 将NSData转为UIImage
    UIImage *decodeImage = [UIImage imageWithData:decodeData];
    
//    NSString *urlString = @"http://imgsrc.baidu.com/forum/eWH%3D240%2C176/sign=183252ee8bd6277ffb784f351a0c2f1c/5d6034a85edf8db15420ba310523dd54564e745d.jpg";
    //    [self.controlView showTitle:titleString coverURLString:urlString fullScreenMode:ZFFullScreenModeLandscape];
    
    [self.controlView showTitle:titleString coverImage:decodeImage fullScreenMode:ZFFullScreenModeLandscape];
}

- (BOOL)shouldAutorotate {
    /// 如果只是支持iOS9+ 那直接return NO即可，这里为了适配iOS8
    return NO;
    return self.player.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.player.isFullScreen && self.player.orientationObserver.fullScreenMode == ZFFullScreenModeLandscape) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    return self.player.isStatusBarHidden;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}


- (void) exactIntent:(NSInteger )tag {
    NSInteger index = tag;
    NSArray *aboutRecArr = [NSArray array];
    for (DLMachineModel *model in self.machineDataSource) {
        if (model.code.integerValue == 6) {
            //关联推荐
            aboutRecArr = model.resultArr;
        }
    }
    NSDictionary *aboutRecDic = aboutRecArr[index];
    [self sendDxactIntentToServer:aboutRecDic];
    kuserManager.isLastMsgVoice = NO;
}
- (void) sendDxactIntentToServer:(NSDictionary *)aboutRecDic {
    
    [self.urls addObject:[NSURL URLWithString:@""]];
    
    NSString *contentString = kSafeString(aboutRecDic[@"showtext"]);
    
    NSMutableDictionary *socketDic = [NSMutableDictionary dictionary];
    
    NSArray *arr = [NSArray arrayWithArray:aboutRecDic[@"entities"]];
    
    NSString *uniqueId = [DLKeyChainManager readUUID];
    if (isEmpty(uniqueId)) {
        uniqueId = [DLKeyChainManager createUUID];
        [DLKeyChainManager saveUUID:uniqueId];
    }
    
    [socketDic setObject:uniqueId forKey:@"user"];
    [socketDic setObject:uniqueId forKey:@"devicecode"];
    [socketDic setObject:uniqueId forKey:@"chatuuid"];
    [socketDic setObject:@"1" forKey:@"online"];
    [socketDic setObject:@"ios" forKey:@"channel"];
    [socketDic setObject:contentString forKey:@"client"];
    [socketDic setObject:@(2) forKey:@"msgtype"];
    [socketDic setObject:aboutRecDic[@"intent"] forKey:@"intent"];
    [socketDic setObject:[arr isKindOfClass:[NSArray class]]?arr:@[] forKey:@"entities"];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:socketDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *sendMsg = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"给服务端发送的明确意图的消息是：%@", sendMsg);
    [self.socket emit:@"message" with:@[sendMsg]];
    
    DLMachineModel *model = [DLMachineModel new];
    model.msgFrom = SocketMsgFrom_self;
    model.msgType = SocketMsgType_text;
    model.content = contentString;
    [self.machineDataSource addObject:model];
    [self.plainTableView reloadData];
    [self tableviewScrollToLastRow];
}

- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.isAutoScroll = NO;
    [scrollView zf_scrollViewWillBeginDragging];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [scrollView zf_scrollViewDidEndDraggingWillDecelerate:decelerate];
}
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScrollToTop];
}
- (void) scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.isAutoScroll == NO) {
        [self.keyboardView endEditing:YES];
    }
    [scrollView zf_scrollViewDidScroll];
}
- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.isAutoScroll = YES;
    [scrollView zf_scrollViewDidEndDecelerating];
}
- (void) playAudioNotification {
    
    [self.player stop];
}
- (void) resetAboutSVYAndTableViewHeight {
    

    [self.plainTableView resetHeight:kScreenSafeAreaHeight - self.falseNavView.height - self.keyboardView.height + self.transformY];
    [self.aboutRecSV resetY:self.keyboardView.top];
    
    self.aboutRecSV.hidden = YES;
    
    self.aboutRecSV.dataSource = @[];
}
- (void) configAboutSV:(DLMachineModel *)model {
    
    self.aboutRecSV.hidden = NO;
    
    [self.aboutRecSV resetY:self.keyboardView.top - self.aboutRecSV.height];
    [self.plainTableView resetHeight:kScreenSafeAreaHeight - kHeightNavigation - self.keyboardView.height + self.transformY - self.aboutRecSV.height];
    
    self.aboutRecSV.dataSource = model.resultArr;
}
- (void) keyboardWillChangeInputTypeNotify {
    if (self.aboutRecSV.isHidden) {
        
        [UIView animateWithDuration:self.duration animations:^{
            [self.plainTableView resetHeight:kScreenSafeAreaHeight - kHeightNavigation - self.keyboardView.height + self.transformY];
            [self.keyboardView resetY:self.plainTableView.bottom];
            
        }];
    } else {
        [UIView animateWithDuration:self.duration animations:^{
            
            [self.plainTableView resetHeight:kScreenSafeAreaHeight - kHeightNavigation - self.keyboardView.height + self.transformY - self.aboutRecSV.height];
            [self.aboutRecSV resetY:self.plainTableView.bottom];
            [self.keyboardView resetY:self.aboutRecSV.bottom];
            
        }];
    }
}
-(void)keyboardWillChangeFrameNotify:(NSNotification*)notify {
    
    // 0.取出键盘动画的时间
    CGFloat duration = [notify.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    self.duration = duration;
    // 1.取得键盘最后的frame
    CGRect keyboardFrame = [notify.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 2.计算控制器的view需要平移的距离
    CGFloat transformY = keyboardFrame.origin.y - kScreenSafeAreaHeight;
    self.transformY = transformY;
//    NSLog(@"++++++++++++++++++%.2f", transformY);
    
    CGFloat visibleAreaHeight = kScreenSafeAreaHeight - kHeightNavigation - self.keyboardView.height + self.transformY;
    self.visibleAreaHeight = visibleAreaHeight;
//    NSLog(@"==================%.2f", visibleAreaHeight);
    
    
    if (self.transformY == 34.000000) {
        NSLog(@"xxxxxxxxxxxxxxxxxxxx系列的设备键盘收起了，不是0，是34 快跑啊");
    }
    
    //34 是x系列
    if (self.transformY != 0 && self.transformY != 34.000000) {
        //键盘展开
        
        if (self.aboutRecSV.isHidden) {
            //关联推荐的sv是隐藏的，没什么影响
            //如果屏幕上可见cell的高度总和比（安全区域高度-导航条高度-键盘-输入框高度）大，那么就需要重新设置table高度 并且需要滚动到最后一个cell，否则不做任何处理
            
            if ([self getVisibleCellsHeight] > visibleAreaHeight) {
                //键盘弹出，需要重新设置y值
//                NSLog(@"键盘弹出，需要重新设置table高度，并且需要滚动到底部");
                [UIView animateWithDuration:self.duration animations:^{
                    [self.plainTableView resetHeight:visibleAreaHeight];
                    [self.keyboardView resetY:self.plainTableView.bottom];
                }];
                
                [self tableviewScrollToLastRow];
            } else {
//                NSLog(@"键盘弹出，需要重新设置table高度，键盘需要重新设置y值,键盘是先添加的，需要移到table前面");
                [UIView animateWithDuration:self.duration animations:^{
                    
                    [self.plainTableView resetHeight:visibleAreaHeight];
                    [self.keyboardView resetY:self.plainTableView.bottom];
                    [self.view bringSubviewToFront:self.keyboardView];
                }];
            }
        } else {
            //关联推荐的sv是显示的，要重新设置控件高度
                //键盘弹出，需要重新设置y值
//                NSLog(@"键盘弹出，关联推荐是显示的，需要重新设置table高度，并且需要滚动到底部");
                [UIView animateWithDuration:self.duration animations:^{
                    
                    [self.plainTableView resetHeight:visibleAreaHeight - self.aboutRecSV.height];
                    
                    [self.aboutRecSV resetY:self.plainTableView.bottom];
                    [self.keyboardView resetY:self.aboutRecSV.bottom];
                    
                }];
                [self tableviewScrollToLastRow];
        }

    } else {
        
        //键盘收起
//        NSLog(@"键盘收起");
        
        if (self.aboutRecSV.isHidden) {
            //关联推荐是隐藏的
            
            [UIView animateWithDuration:self.duration animations:^{
                [self.plainTableView resetHeight:visibleAreaHeight];
                [self.keyboardView resetY:self.plainTableView.bottom];
            }];
            
        } else {
            //关联推荐是显示的
//            NSLog(@"==============%d", self.keyboardView.keyboardType);
            //如果当前是文字输入模式
            [UIView animateWithDuration:self.duration animations:^{
                [self.plainTableView resetHeight:visibleAreaHeight - self.aboutRecSV.height];
                [self.aboutRecSV resetY:self.plainTableView.bottom];
                [self.keyboardView resetY:self.aboutRecSV.bottom];
                
            }];
        }
        
    }
}
- (void) tableviewScrollToLastRow {
    //new
    self.isAutoScroll = YES;
    
    if (self.machineDataSource.count > 0) {
        if ([self.plainTableView numberOfRowsInSection:0] > 0) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:([self.plainTableView numberOfRowsInSection:0]-1) inSection:0];
            [self.plainTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        }
    }
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
//    self.navigationController.navigationBarHidden = NO;
//    self.navigationController.navigationBar.translucent = NO;
    
    {
        
        self.hiddenNavigationBottomLine = YES;
        self.navigationController.navigationBarHidden = YES;
        self.navigationController.navigationBar.translucent = YES;
    }
    
    [self doSomething];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotify:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeInputTypeNotify) name:@"keyboardChangeInputType" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableviewReloadData) name:@"plainTableShouldReloadData" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iflyDidTransformVoiceToString:) name:@"iflyDidTransformVoiceToString" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playAudioNotification) name:@"playAudioNotification" object:nil];
    
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.keyboardView endEditing:YES];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
}
- (void) initDataSource {
    self.machineDataSource = [NSMutableArray array];
    DLMachineModel *model = [DLMachineModel new];
    model.content = @" Hi 我是小语";
    model.isDefaultMachineMsg = NO;
    model.msgType = SocketMsgType_text;
    model.msgFrom = SocketMsgFrom_other;
    model.isServerMsgCanTransformToVoice = NO;
    [self.machineDataSource addObject:model];
    
    self.urls = [NSMutableArray array];
    [self.urls addObject:[NSURL URLWithString:@""]];
}
- (CGFloat) getVisibleCellsHeight {
    
    CGFloat visibleCellsHeight = 0;
    NSArray *arr = [self.plainTableView visibleCells];
    for (UITableViewCell *cell in arr) {
        visibleCellsHeight += cell.height;
    }
    
//    NSLog(@"屏幕上可见cell总高度是%f", visibleCellsHeight);
    return visibleCellsHeight;
}

- (void) viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self.player stop];
    
    IFlySpeechSynthesizer *iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    [iFlySpeechSynthesizer stopSpeaking];
}

- (void) dealloc {
    NSLog(@"dealloc ======> %@", NSStringFromClass([self class]));
    
    [self.socket disconnect];
    
    [IFlySpeechSynthesizer destroy];
    
    IFlySpeechSynthesizer *iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    [iFlySpeechSynthesizer stopSpeaking];
    
    [self.keyboardView.iFlySpeechRecognizer destroy];
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.machineDataSource.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DLMachineModel *model = self.machineDataSource[indexPath.row];
    return [DLMachineBaseCell getCellHeightWithModel:model];
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    /**
     SocketMsgType_text = 10,//普通文字
     SocketMsgType_video,//视频
     SocketMsgType_image,//图片
     SocketMsgType_kLineChart,//k线图
     SocketMsgType_pieChart,//饼图
     SocketMsgType_histogram,//柱状图
     SocketMsgType_lineChart,//折线图(分时图)
     SocketMsgType_form,//图表
     SocketMsgType_information//资讯
     */
    DLMachineModel *machineModel = self.machineDataSource[indexPath.row];
    
    if (machineModel.msgType == SocketMsgType_text) {
        //普通文字
//        NSLog(@"消息展示->普通文字");
        DLMachineNormalTC *machineNormalTC = [tableView dequeueReusableCellWithIdentifier:@"DLMachineNormalTC"];
        machineNormalTC.tag = 10010;
        machineNormalTC.normalModel = machineModel;
        return machineNormalTC;
    } else if (machineModel.msgType == SocketMsgType_video) {
        //视频
//        NSLog(@"消息展示->视频");
        DLMachineVideoTC *machineVideoTC = [tableView dequeueReusableCellWithIdentifier:@"DLMachineVideoTC" forIndexPath:indexPath];
        [machineVideoTC setDelegate:self withIndexPath:indexPath];
        machineVideoTC.videoModel = machineModel;
        [machineVideoTC setNormalMode];
        return machineVideoTC;
    } else if (machineModel.msgType == SocketMsgType_image) {
        //图片
//        NSLog(@"消息展示->图片");
        DLMachineImageTC *machineImageTC = [tableView dequeueReusableCellWithIdentifier:@"DLMachineImageTC"];
        machineImageTC.imageModel = machineModel;
        return machineImageTC;
    } else if (machineModel.msgType == SocketMsgType_kLineChart ||
               machineModel.msgType == SocketMsgType_pieChart ||
               machineModel.msgType == SocketMsgType_histogram ||
               machineModel.msgType == SocketMsgType_timeSharing) {
        //k线、饼图、柱状图、折线图(分时图)
//        NSLog(@"消息展示->图表");
        DLMachineChartsTC *machineChartsTC = [tableView dequeueReusableCellWithIdentifier:@"DLMachineChartsTC"];
        machineChartsTC.chartsModel = machineModel;
        return machineChartsTC;
    } else if (machineModel.msgType == SocketMsgType_form) {
        //表格
        NSLog(@"消息展示->表格");
        DLMachineFormTC *machineFormTC = [tableView dequeueReusableCellWithIdentifier:@"DLMachineFormTC"];
        machineFormTC.formModel = machineModel;
        return machineFormTC;
    } else if (machineModel.msgType == SocketMsgType_singleSelect) {
        //单选
//        NSLog(@"消息展示->单选");
        DLSingleSelectTC *singleSelectTC = [tableView dequeueReusableCellWithIdentifier:@"DLSingleSelectTC"];
        singleSelectTC.singleSelectModel = machineModel;
        
        singleSelectTC.singleSelectTitleLabelTapBlock = ^(NSInteger titleLabelTag) {
            NSArray *arr = machineModel.resultArr;
            [self sendDxactIntentToServer:arr[titleLabelTag]];
        };
        return singleSelectTC;
    } else if (machineModel.msgType == SocketMsgType_information){
        //资讯 SocketMsgType_information
//        NSLog(@"消息展示->资讯");
        DLMachineInfoTC *machineInfoTC = [tableView dequeueReusableCellWithIdentifier:@"DLMachineInfoTC"];
        machineInfoTC.infoModel = machineModel;
        return machineInfoTC;
    } else {
        NSLog(@"消息展示->服务器返回code==9的消息");
        DLMachineBaseCell *machineBaseCell = [tableView dequeueReusableCellWithIdentifier:@"DLMachineBaseCell"];
        return machineBaseCell;
    }
    
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    /// 如果正在播放的index和当前点击的index不同，则停止当前播放的index
    if (self.player.playingIndexPath != indexPath) {
        NSString *currentRowVideoUrl = kFormatString(self.urls[indexPath.row]);
        if (currentRowVideoUrl.length > 0) {
            [self.player stopCurrentPlayingCell];
        }
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
